// 这里把 index.js 也作为一个模块去定义并加载，这样才其他地方可以通过 require('./index') 来加载它，如果用 seajs.use 的话就不行
define(function(require, exports, module){
  var $ = require('../lib/jquery');  // jquery模块
  var bs = require('../lib/bootstrap-3.0.0-dist/dist/js/bootstrap');
  var _ = require('../main');  // main模块
  var bsm = require('../lib/bootstrap-treeview.min');
  var jqc = require('../lib/jquery.contextify.min');

  var commonurl=_.getUrl();
  var ticket = _.getTicket();
  // var filePath;
  //约束输入字数
  $("#group_name").keyup(function(){
    if($("#group_name").val().length > 20){
      $("#group_name").val( $("#group_name").val().substring(0,20));
      confirm("提示","字数不能超过20个！");
    }
  });
  $("#group_adm_name").keyup(function(){
    if($("#group_adm_name").val().length > 20){
      $("#group_adm_name").val( $("#group_adm_name").val().substring(0,20));
      confirm("提示","字数不能超过20个！");
    }
  });

  $("#remark").keyup(function(){
     if($("#remark").val().length > 255){
        $("#remark").val( $("#remark").val().substring(0,255));
        confirm("提示","字数不能超过255个！");
     }
  });

    $(".left_table table").on("click","tr",function(){
                 _.slideDown($(".table_detail"));
                 _.addActive($(this),$(this).siblings());
                  //拿到这一行的信息在表单展示
                 //var user=$(this).find("td").eq(1).html();
                });

    $.ajax({
        url:commonurl+"nginx/getSystem",
        type: 'GET', 
        headers: {"Authorization":ticket}, 
        Accept: 'application/json',
        success: function(json){
          var parameters=json;
         filePath=_.getFilePath(parameters[0].value);
        $.ajax({ 
          url: commonurl+"nginx/readUpStream?address="+filePath,
          type: 'GET', 
          headers: {"Authorization":ticket}, 
          //data:{username:$("#username").val(), content:$("#content").val()}, 
          success: function(json){
            var admins_list=json;
            //遍历表格
            $.each(admins_list, function(commentIndex, comment){
                var templates="<tr><td>"+admins_list[commentIndex].ip+"</td><td>"+admins_list[commentIndex].port+"</td><td>"+admins_list[commentIndex].weight+"</td><td>"+admins_list[commentIndex].max_fails+"</td><td>"+admins_list[commentIndex].fail_timeout+"</td><td>"+admins_list[commentIndex].state+"</td></tr>"
                $(".left_table table").append(templates);
                $(".left_table table").on("click","tr",function(){
                 _.slideDown($(".table_detail"));
                 _.addActive($(this),$(this).siblings());
                  //拿到这一行的信息在表单展示
                 //var user=$(this).find("td").eq(1).html();
                  if($(this).find("td").eq(0).html()==admins_list[commentIndex].ip&&$(this).find("td").eq(1).html()==admins_list[commentIndex].port){
                    $("#group_number").val(admins_list[commentIndex].ip);
                    $("#group_name").val(admins_list[commentIndex].state);
                    $("#group_adm_name").val(admins_list[commentIndex].weight);
                    $("#group_time").val(admins_list[commentIndex].max_fails);
                    $("#group_root_name").val(admins_list[commentIndex].port);
                    $("#remark").val(admins_list[commentIndex].fail_timeout);
                  }
                });
            });
        var tree=json.tree;
          //点击单个表格出现下面的表单信息
  
      }});
        $.ajax({ 
            url: commonurl+"nginx/readConf?address="+filePath,
            type: 'GET',
            headers: {"Authorization":ticket},  
            // data:{remark:remark}, 
            success: function(json){
              var confText=json;
              // for(var i=0;i<confText.length;i++){
              //   $("#confTxT").add(confText[i].value);
              // }
              $("#confTxT").val(confText); 
            },
            error:function(){
              $("#confTxT").val("文件加载失败");
            }
          }); 
        },
        error:function(json){
          confirm("提示","系统出错路径检查不到，检查数据库路径是否正确");
        }
        });

  //点击新增用户，弹出modal
  $(".btn_add").on("click",function(){
     // $("#nowTime").val(_.formatDate(new Date(), 'yyyy-MM-dd HH:mm:ss'));
  });
  $(".addSave").on("click",function(){
    var fail_timeout=$("#addTimeOut").val();
    var nginx_ip=$("#addIp").val();
    var max_fails=$("#addfail").val();
    var port=$("#addport").val();
    var weight=$("#weight").val();

    if (fail_timeout==null||nginx_ip==null||max_fails==null||port==null||weight==null) {
      confirm("提示","信息不完整请补充完信息");
    }else{
          $.ajax({ 
            url: commonurl+"nginx/addUpstream?address="+filePath,
            type: 'POST',
            headers: {"Authorization":ticket},  
            contentType: 'application/json; charset=utf-8',
            data: JSON.stringify({"fail_timeout":fail_timeout,"ip":nginx_ip,"max_fails":max_fails,"port":port,"state":false,"weight": weight}), 
              success: function(json){
                    alert("新建成功");
                    setTimeout(function(){  //使用  setTimeout（）方法设定定时1000毫秒
                               window.location.reload();//页面刷新
                    },1000);

                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    if(XMLHttpRequest.status ==415 ){
                             alert("文件错误");
            }         else{
                          alert("系统错误");
                        }
                      }
              });
    }
  })

 //点击保存设置
  $(".save").on("click",function(){
    var fail_timeout=$("#remark").val();
    var nginx_ip=$("#group_number").val();
    var max_fails=$("#group_time").val();
    var port=$("#group_root_name").val();
    var weight=$("#group_adm_name").val();
    $.ajax({ 
    url: commonurl+"nginx/putUpstream?address="+filePath,
    type: 'PUT',
    headers: {"Authorization":ticket},  
    contentType: 'application/json; charset=utf-8',
    data: JSON.stringify({"fail_timeout":fail_timeout,"ip":nginx_ip,"max_fails":max_fails,"port":port,"state":false,"weight": weight}), 
    success: function(json){
        alert("新建成功");
        setTimeout(function(){  //使用  setTimeout（）方法设定定时1000毫秒
                    window.location.reload();//页面刷新
        },1000);
      },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
               if(XMLHttpRequest.status ==415 ){
                    alert("文件错误"+errorThrown);
               }else{
                alert("系统错误"+errorThrown);
               }
            }
    });
  })
        $(".btn_reset").on("click",function(){
              var fail_timeout=$("#remark").val();
              var nginx_ip=$("#group_number").val();
              var max_fails=$("#group_time").val();
              var port=$("#group_root_name").val();
              var weight=$("#group_adm_name").val();
              $.ajax({ 
                  url: commonurl+"nginx/delUpstream?address="+filePath,
                  type: 'DELETE',
                  headers: {"Authorization":ticket},  
                  contentType: 'application/json; charset=utf-8',
                  data: JSON.stringify({"fail_timeout":fail_timeout,"ip":nginx_ip,"max_fails":max_fails,"port":port,"state":false,"weight": weight}), 
                  success: function(json,XMLHttpRequest, textStatus, errorThrown){
                      alert("成功");
                      setTimeout(function(){  //使用  setTimeout（）方法设定定时1000毫秒
                      window.location.reload();//页面刷新
                      },1000);
                    },
                  error: function(XMLHttpRequest, textStatus, errorThrown) {
                        alert("失败");
                    }
                     });
          })
    /*右键菜单*/
    var options = {items:[
    {header: '菜单'},
    {text: '新增', href: '#'},
    {text: '删除', onclick: function(e) {
      alert('删除 ');
    }}

  ]}
  $('#tree').contextify(options);

});
  